package hot100.h0912;

import java.util.LinkedList;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 最长有效括号
 * @date 2024/9/12 16:41
 */
public class LongestValidBracket {
    public static void main(String[] args) {
        String s = "(()()";
        System.out.println(longestValidParentheses(s));
    }

    public static int longestValidParentheses(String s) {
        LinkedList<Integer> stack = new LinkedList<>();
        stack.push(-1);
        int maxLen = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (!stack.isEmpty()) {
                    maxLen = Math.max(maxLen, i - stack.peek());
                }else {
                    stack.push(i);
                }
            }
        }
        return maxLen;
    }
}
